<template>
  <el-card>
    <template #header>
      <h3 v-text="t('Signal monitor')"></h3>
    </template>
    
    <el-row :gutter="12" v-for="monitor in monitorStore.monitors" :key="monitor.id">
      <el-col :span="24">
        <div class="monitor-container">
          <el-row :gutter="8" style="align-items: center;">
            <el-col :span="12">
              <div class="signal-info">
                <div class="signal-name">{{ monitor.name }}</div>
                <div class="signal-value">{{ monitor.value !== null && monitor.value !== undefined ? monitor.value : '---' }}</div>
              </div>
            </el-col>
            <el-col :span="10">
              <div class="trend-chart">
                <canvas :ref="el => setCanvasRef(el, monitor.id)"></canvas>
              </div>
            </el-col>
            <el-col :span="2">
              <el-button 
                type="danger" 
                size="small" 
                @click="monitorStore.removeMonitor(monitor.id)"
                style="width: 100%;">
                ×
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
    
    <el-row justify="center">
      <el-col :span="6">
        <el-button 
          type="primary" 
          @click="monitorStore.showSignalAdder"
          :disabled="!monitorStore.canAddMore"
          style="width: 100%;">
          +
        </el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { useSignalMonitorStore } from '@/stores/signalMonitor'
import { useLanguageStore } from '@/stores/language'

const monitorStore = useSignalMonitorStore()
const languageStore = useLanguageStore()
const canvasRefs = ref(new Map())

// 在组件挂载时加载保存的信号ID
onMounted(() => {
  monitorStore.loadFromLocalStorage()
})

// 翻译函数
const t = (key) => {
  const translations = {
    'Signal monitor': {
      'en': 'Signal monitor',
      'zh': '信号监控'
    }
  }
  return translations[key]?.[languageStore.isChinese ? 'zh' : 'en'] || key
}

// 设置canvas引用
function setCanvasRef(el, monitorId) {
  if (el) {
    monitorStore.setCanvasRef(el, monitorId)
  }
}
</script>

<style scoped>
.monitor-container {
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  padding: 12px;
  background-color: var(--el-bg-color-page);
}
.signal-value {
  color: var(--el-color-primary);
}

.trend-chart {
  height: 40px;
  overflow: hidden;
  background-color: var(--el-fill-color-darker);
  border-radius: 4px;
}

.trend-chart canvas {
  width: 100%;
  height: 100%;
}
</style> 